<?php

namespace App\Controllers;

use App\Models\NewsModel;

class News extends BaseController
{
    public function index()
    {
        $model = new NewsModel();

        $data = [
            'news' => $model->getNews(),
            'title' => "ChengZizhuo's News archive",
        ];

        return view('templates/header', $data)
            . view('news/index', $data)
            . view('templates/footer', $data);
    }

    public function view($slug = null)
    {
        $model = new NewsModel();

        $data['news'] = $model->getNews($slug);

        if (empty($data['news'])) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Cannot find the news item: ' . $slug);
        }

        $data['title'] = $data['news']['title'];

        return view('templates/header', $data)
            . view('news/view', $data)
            . view('templates/footer', $data);
    }

    public function new()
    {
        helper('form');

        return view('templates/header', ['title' => 'Create a news item'])
            . view('news/create')
            . view('templates/footer');
    }

    public function create()
    {
        helper('form');

        $data = $this->request->getPost(['title', 'body']);

        // Checks whether the submitted data passed the validation rules.
        if (
            !$this->validateData($data, [
                'title' => 'required|max_length[255]|min_length[3]',
                'body' => 'required|max_length[5000]|min_length[10]',
            ])
        ) {
            // The validation fails, so returns the form.
            return $this->new();
        }

        // Gets the validated data.
        $post = $this->validator->getValidated();

        $model = model(NewsModel::class);

        $model->save([
            'title' => $post['title'],
            'slug' => url_title($post['title'], '-', true),
            'body' => $post['body'],
        ]);

        return view('templates/header', ['title' => 'Create a news item'])
            . view('news/success')
            . view('templates/footer');
    }

    public function delete(?int $id = null)
    {
        // 验证ID是否存在
        if ($id === null) {
            return redirect()->to(site_url('news'))->with('error', 'News ID not specified');
        }

        // 加载模型并删除数据
        $newsModel = new NewsModel();
        // 在CodeIgniter中，delete方法通常直接接受主键值
        $deleteSuccess = $newsModel->delete($id);

        // 跳转至删除结果页
        if ($deleteSuccess) {
            return view('news/success_delete', [
                'title' => 'Delete a news item',
                'message' => 'News item deleted successfully!'
            ]);
        } else {
            return view('news/success_delete', [
                'title' => 'Delete a news item',
                'message' => 'Failed to delete news item.'
            ]);
        }
    }
}